package ticketbooking;

import java.io.Serializable;
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
 
public class AES {
        
        public static byte[] IV(SecretKey secretKey) throws Exception {
                
                Cipher cipher = cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                AlgorithmParameters params = cipher.getParameters();
                byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
                return iv;
        }
        
        public static byte[] encrypt(String plainText, SecretKey secretKey) throws Exception {
                
                Cipher cipher = cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
               
                byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF-8"));
                
               return cipherText;
        }
         
        public static String decrypt(byte[] cipherText, SecretKey secretKey, byte[] iv) throws Exception {
         
                Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
                
                String plainText = new String(cipherDecrypt.doFinal(cipherText), "UTF-8");
         
                return plainText;
        }
        
        public static SealedObject encryptObj(Object plainObj, SecretKey secretKey) throws Exception {
                
                assert(plainObj instanceof Serializable);
                
                Cipher cipher = cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
              
                SealedObject SO = new SealedObject((Serializable)plainObj, cipher);
        
        
                return SO;
        }
         
        public static Object decryptObj(SealedObject EO, SecretKey secretKey, byte[] iv) throws Exception {
                
                Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
                
                Object plainObj = (Object) EO.getObject(cipherDecrypt);
                
                return plainObj;
        }
    
}